<template>
  <view class="u-page">
    <up-list show-scrollbar :scroll-into-view="scrollToId" :upper-threshold="100" scroll-with-animation
             :height="listHeight" @scrolltoupper="scrolltoupper" @scroll="scroll">
      <up-list-item v-for="(item) in messageList" :id="'item-'+item.id" :key="item.id">
        <view class="chat-item">
          <uv-chat
            :me="item.sendUserId === userStore.userId"
            :avatar="item.sendUserAvatar"
            :content="item.content"
            :nick="item.sendUserName"
            :type="item.type"
            :other="item"
            @avatar-click-db="handleAvatarClickDb"
            @avatar-click="handleAvatarClick"
          >
            <template #content>
              <uv-chat-text
                v-if="item.type === 'TEXT'"
                :content="item.content"
                :me="item.sendUserId === userStore.userId"
              ></uv-chat-text>
              <uv-chat-image
                v-if="item.type === 'IMAGE'"
                :src="item.content"
                :upload-flag="item.uploadFlag"
                :me="item.sendUserId === userStore.userId"
              ></uv-chat-image>
              <uv-chat-video
                v-if="item.type === 'VIDEO'"
                :src="item.content"
                :video-cover="item.videoCover"
                :upload-flag="item.uploadFlag"
                :me="item.sendUserId === userStore.userId"
              ></uv-chat-video>


            </template>
          </uv-chat>
        </view>

      </up-list-item>
    </up-list>
    <uv-chat-input
      ref="uvChatInputRef"
      @send-call-back="sendMessageCallBack"
      @set-list-height="setListHeight"
    >
    </uv-chat-input>
  </view>
</template>

<script lang="ts" setup>
import { to } from 'await-to-js';
import { IMMessageType } from '@/enmus/IMMessageEnum';
import { MessageVo, ChatMessageVo } from '@/types/IMMessageDTO';
import useIMStore from '@/store/modules/im';
import useUserStore from '@/store/modules/user';

const imStore = useIMStore();
const userStore = useUserStore();


const listHeight = ref('87.7vh');
const roolFlag=ref(false);

// 输入组件
const uvChatInputRef = ref(null);

// 消息列表
const scrollToId = ref(null);
const messageList = ref<ChatMessageVo[]>([]);
const total = ref(0);
const params = ref({
  pageSize: 50,
  pageNum: 1
});


// 设置消息列表高度 并滚动到底部
const setListHeight = (height: string, scrollToBottom: boolean) => {
  listHeight.value = height;
  if (scrollToBottom && messageList.value.length > 0) {
    scrollTo(messageList.value[messageList.value.length - 1].id);
  }
};


// 获取消息列表
const getMessageList = async () => {
  const res = await uni.$u.http.get(`/work/chatGroup/chatGroupList`, {
    params: params.value
  });
  const rows = res.rows.reverse();
  messageList.value = [...rows, ...messageList.value];
  total.value = res.total;
  if (rows.length > 0) {
    scrollTo(rows[rows.length - 1].id);
  }


};

// 发送消息
const sendMessageCallBack = async (message: ChatMessageVo) => {
  messageList.value.push(message);
  scrollTo(message.id);
};


//向上滚动时，获取数据
const scrolltoupper = async () => {
  if (messageList.value.length < total.value) {
    params.value.pageNum++;
    await getMessageList();
  }
};
//滚动时触发
const scroll = () => {
  // if(roolFlag.value)return;
  // uni.hideKeyboard();
  // uvChatInputRef.value.closeFunctionBody();
  // listHeight.value = '87.3vh';
};
//滚动到指定item
const scrollTo = (id: string) => {
  roolFlag.value=true
  scrollToId.value = null;
  nextTick(() => {
    scrollToId.value = 'item-' + id;
    setTimeout(()=>{
      roolFlag.value=false
    },3000);
  });
};


// 头像单击
const handleAvatarClick = (data: any) => {
  console.log(data);
};
// 头像双击
const handleAvatarClickDb = (data: any) => {
  console.log(data);
};


//接收到im消息
const receiveData = (data: MessageVo) => {
  const chatMessageInfo: ChatMessageVo = JSON.parse(data.messageInfo);
  messageList.value.push(chatMessageInfo);
  scrollTo(chatMessageInfo.id);
  imStore.set(IMMessageType.CHAT_GROUP, 0);
};
//接收到im消息 -媒体文件上传成功
const receiveMediaUploadOK = (data: MessageVo) => {
  const chatMessageInfo = JSON.parse(data.messageInfo);
  const item: ChatMessageVo = messageList.value.find(item => item.id == chatMessageInfo.mediaId);
  item.uploadFlag = true;
  if (chatMessageInfo.videoUrl) {
    item.content = chatMessageInfo.videoUrl;
  }
};

// 初始化
onLoad(async () => {
  await getMessageList();
  uni.$on(IMMessageType.CHAT_GROUP, receiveData);
  uni.$on(IMMessageType.CHAT_GROUP_MEDIA_UPLOAD_OK, receiveMediaUploadOK);
});

onReady(() => {
  uvChatInputRef.value.setHeight();
});
onUnload(() => {
  uni.$off(IMMessageType.CHAT_GROUP, receiveData);
  uni.$off(IMMessageType.CHAT_GROUP_MEDIA_UPLOAD_OK, receiveMediaUploadOK);
});
onShow(() => {
  imStore.set(IMMessageType.CHAT_GROUP, 0);
});


</script>

<style scoped lang="scss">
.u-page {
  background-color: #f4f5f7;
  padding: 0;
}

.chat-item {
  padding: 10px;
}




</style>
